package im.zhihao.zhdisk.module.user.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import im.zhihao.zhdisk.core.util.AjaxJson;
import im.zhihao.zhdisk.module.link.model.entity.UserShortLink;
import im.zhihao.zhdisk.module.link.service.ShortLinkService;
import im.zhihao.zhdisk.module.user.model.convert.SystemUserConvert;
import im.zhihao.zhdisk.module.user.model.dto.SystemUserDTO;
import im.zhihao.zhdisk.module.user.model.entity.SystemUser;
import im.zhihao.zhdisk.module.user.model.request.*;
import im.zhihao.zhdisk.module.user.model.result.SystemUserResult;
import im.zhihao.zhdisk.module.user.service.SystemUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

@RestController
@Api(tags = "用户基础模块")
@ApiSort(1)
@Slf4j
@RequestMapping("/user")
public class UserController {


    @Resource
    private SystemUserService systemUserService;

    @Value("${spring.datasource.driver-class-name}")
    private String datasourceDriveClassName;

    @Resource
    private SystemUserConvert systemUserConvert;

    @Resource
    private ShortLinkService shortLinkService;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "新增用户")
    @PostMapping
    public AjaxJson<?> addUser(@Valid @RequestBody AddUserRequest addUserRequest) {
        SystemUserDTO systemUser = new SystemUserDTO();
        BeanUtils.copyProperties(addUserRequest, systemUser);
        systemUser.setPassword(SecureUtil.md5(addUserRequest.getPassword()));
        systemUserService.addSystemUser(systemUser);
        return AjaxJson.getSuccess("新增用户成功");
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "修改用户密码")
    @PutMapping("/password")
    public AjaxJson<?> updatePwd(@Valid @RequestBody UpdateUserPasswordRequest updateUserPasswordRequest) {
        SystemUserDTO systemUser = new SystemUserDTO();
        BeanUtils.copyProperties(updateUserPasswordRequest, systemUser);
        String password = systemUser.getPassword();
        if (StrUtil.isNotEmpty(password)) {
            systemUser.setPassword(SecureUtil.md5(password));
        }
        systemUserService.updateSystemUser(systemUser);
        return AjaxJson.getSuccess();
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "修改用户基本信息")
    @PutMapping
    public AjaxJson<?> updateBase(@Valid @RequestBody UpdateUserBaseRequest updateUserBaseRequest) {
        SystemUserDTO systemUser = new SystemUserDTO();
        BeanUtils.copyProperties(updateUserBaseRequest, systemUser);
        systemUserService.updateSystemUser(systemUser);
        return AjaxJson.getSuccess();
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "查询用户列表")
    @PostMapping("/list")
    public AjaxJson<?> listUser(@RequestBody ListSystemUserRequest queryObj) {
        // 分页和排序
        boolean asc = Objects.equals(queryObj.getOrderDirection(), "asc");
        Page<SystemUser> pages = new Page<SystemUser>(queryObj.getPage(), queryObj.getLimit())
                .addOrder(new OrderItem(queryObj.getOrderBy(), asc));


        String dateFrom = queryObj.getDateFrom();
        String dateTo = queryObj.getDateTo();

        boolean isSqlite = StrUtil.equals(datasourceDriveClassName, "org.sqlite.JDBC");
        if (isSqlite) {
            if (StrUtil.isNotEmpty(queryObj.getDateFrom())) {
                dateFrom = Convert.toStr(DateUtil.parseDateTime(dateFrom).getTime());
            }
            if (StrUtil.isNotEmpty(queryObj.getDateTo())) {
                dateTo = Convert.toStr(DateUtil.parseDateTime(dateTo).getTime());
            }
        }

        // 搜索条件
        QueryWrapper<SystemUser> queryWrapper =
                new QueryWrapper<>(new SystemUser())
                        .eq(StrUtil.isNotEmpty(queryObj.getUsername()), "username", queryObj.getUsername())
                        .like(StrUtil.isNotEmpty(queryObj.getNickname()), "nickname", queryObj.getNickname())
                        .ge(StrUtil.isNotEmpty(queryObj.getDateFrom()), "create_time", dateFrom)
                        .le(StrUtil.isNotEmpty(queryObj.getDateTo()), "create_time", dateTo);

        // 执行查询
        Page<SystemUser> selectResult = systemUserService.selectPage(pages, queryWrapper);

        // 转换为结果集
        Stream<SystemUserResult> systemUserResultList = selectResult.getRecords().stream().map(systemUser -> {
            return systemUserConvert.entityToResult(systemUser);
        });
        return AjaxJson.getPageData(selectResult.getTotal(), systemUserResultList);
    }
    @PostMapping("/shortlink/list")
    public AjaxJson<?> listUS(@RequestBody UserShortLink queryObj) {
        String strLoginId = StpUtil.getLoginId().toString();
        Integer userId = null;
        if (!strLoginId.equals("admin")){
            userId = Integer.parseInt(strLoginId);
        }

        // 执行查询
        List<UserShortLink> selectResult = shortLinkService.selectListUS(queryObj.getUserId(), queryObj.getShortLinkId());
        return AjaxJson.getSuccessData(selectResult);
    }

    @PostMapping("/shortlink/add")
    public AjaxJson<?> addUS(@RequestBody @Valid UserShortLink queryObj) {

        // 执行查询
        shortLinkService.addUS(queryObj.getUserId(), queryObj.getShortLinkId());
        return AjaxJson.getSuccess();
    }

    @PostMapping("/shortlink/del")
    public AjaxJson<?> delUS(@RequestBody @Valid UserShortLink queryObj) {

        // 执行查询
        boolean isDel = shortLinkService.delUS(queryObj.getUserId(), queryObj.getShortLinkId());
        return AjaxJson.getSuccess();
    }


    @ApiOperationSupport(order = 2)
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户 id", required = true, dataTypeClass = Integer.class)
    public AjaxJson<Void> deleteById(@PathVariable Integer id) {
        systemUserService.removeById(id);
        return AjaxJson.getSuccess();
    }

    @ApiOperationSupport(order = 2)
    @GetMapping("/{id}")
    @ApiOperation(value = "查询用户")
    @ApiImplicitParam(paramType = "path", name = "id", value = "用户 id", required = true, dataTypeClass = Integer.class)
    public AjaxJson<?> findById(@PathVariable Integer id) {
        SystemUser systemUser = systemUserService.findById(id);
        SystemUserResult systemUserResult = systemUserConvert.entityToResult(systemUser);
        return AjaxJson.getSuccessData(systemUserResult);
    }
}
